package com.edu.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 
 * @author wms
 * 所有的Servlet都要继承此类
 * 根据访问路径来进行Servlet的方法分发
 */
public class BaseServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码方式
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		//获取方法访问路径
		String url = request.getRequestURI();
		//获取最后一段访问路径
		int index = url.lastIndexOf("/");
		String methodName = url.substring(index+1);
		System.out.println(url);
		System.out.println(methodName);
		//获取对应servler的字节码文件
		Class<? extends BaseServlet> cla = this.getClass();
		try {
			//获取对应的方法
			Method method = cla.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//执行方法
			method.invoke(this,request,response);
		} catch (NoSuchMethodException e) {
			System.out.println(methodName);
			System.out.println("访问路径:"+url);
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
